#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2014年10月13日

@author: chenyongbing
'''
from django.http import HttpResponse,HttpResponseNotFound
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils import simplejson 
from django.contrib.auth.decorators import login_required  
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from forms import *
import re,os,datetime

import commands
cdir = os.path.dirname(os.path.abspath(__file__))

from similarFlow import SimilarFlow
mySimilarFlow = SimilarFlow()

from similar_rssi_calculation import *
mySimilarRssiCalculation = SimilarRssiCalculation()

sys.path.append(os.path.join(current_dir,'../'))
from base.retail_datas import myRetailDatas
from base.form_datas import FormDatas
myFormDatas = FormDatas()
import json

from base.time_method import myTimeMethod

import logging
def get_slist_between_st_et(st,et):
    u'''获取2个时间间的所有日期'''
    dlist = []
    count = 0
    nday = (datetime.date(int(st[:4]),int(st[5:7]),int(st[8:]))+ datetime.timedelta(-1)).strftime('%Y-%m-%d')
    while nday < et:
        nday = (datetime.date(int(st[:4]),int(st[5:7]),int(st[8:]))+ datetime.timedelta(count)).strftime('%Y-%m-%d')
        count+=1
        dlist.append(nday)
    return dlist




def analyzeImportRealData(real_data):
    customer_datas = {}
    flow_datas = {}
    for line in real_data.split('\n'):
        lineList = line.split(',')
        if len(lineList)<2:continue
        day = lineList[0]
        real_customer=lineList[1]
        try:
            real_flow = lineList[2]
        except:real_flow='0'
        day = day.strip()
        if not re.search('^[\d]{4}-[\d]{2}-[\d]{2}$',day):continue
        real_customer = real_customer.strip()
        real_flow = real_flow.strip()
        if re.search('^[\d]+$',real_customer):
            customer_datas[day] = real_customer
        if re.search('^[\d]+$',real_flow):
            flow_datas[day] = real_flow
    return customer_datas,flow_datas


def similar_flow_expect_rssi(request):
    if request.method=='POST':
        pass



#@login_required      
def calculate_simlar_rssi(request):
    compGroups = myRetailDatas.get_comp_and_groups()
    
    if request.method == 'POST':
        form = ExpectRssiForm2(request.POST,error_class=DivErrorList)
    else:
        form = ExpectRssiForm2(error_class=DivErrorList)
    groups = []
    comps = []
    for compGroup in compGroups.values():
        comps.append([str(compGroup['id']),compGroup['name']])
        for group in compGroup['groups']:
            groups.append(["%s:%s"%(compGroup['id'],group['id']),group['name']])
    form.fields['shop_group'].choices = groups
    form.fields['comp_group'].choices = comps
    
    if request.method == 'POST':
        
        if form.is_valid():
            customer_weekday_avg_cnt = int(request.POST['customer_weekday_avg_cnt'])
            customer_weekend_avg_cnt = int(request.POST['customer_weekend_avg_cnt'])
            customer_min_rssi = int(request.POST['customer_min_rssi'])
            customer_max_rssi = int(request.POST['customer_max_rssi'])
           # print real_data
            walkby_time_list = dict(request.POST)['walkby_time']
            opening_weekend = request.POST['opening_weekend']
            opening_weekday = request.POST['opening_weekday']
            startTime = request.POST['startTime']
            endTime = request.POST['endTime']
            wifi_open_rate = request.POST['wifi_open_rate']
            customer_weekday_avg_cnt = int(int(customer_weekday_avg_cnt) * float(wifi_open_rate)/100)
            customer_weekend_avg_cnt = int(int(customer_weekend_avg_cnt) * float(wifi_open_rate)/100)
            opening_time = {'opening_weekday':opening_weekday,'opening_weekend':opening_weekend}
            try:
                group = request.POST['shop_group'].split(':')[-1]
            
                comp_group = request.POST['comp_group']

    
                role_name = 'all_customer'
                datas = mySimilarRssiCalculation.show_expect_rssi_order_by_similarity_coefficient(group=group, startTime=startTime, endTime=endTime, customer_weekday_avg_cnt=int(customer_weekday_avg_cnt),customer_weekend_avg_cnt=int(customer_weekend_avg_cnt) ,customer_min_rssi=int(customer_min_rssi), customer_max_rssi=int(customer_max_rssi), walkby_list=walkby_time_list)
                if datas==[]:datas=None
            except:
                group = None
                datas = None
            return render_to_response('zmDataTuning/similar_expect_rssi.html',{'form':form,'datas':datas,'compGroups':compGroups},context_instance=RequestContext(request))
        else:
            
            return render_to_response('zmDataTuning/similar_expect_rssi.html',{'form':form,'compGroups':compGroups},context_instance=RequestContext(request))

    else:
        
        return render_to_response('zmDataTuning/similar_expect_rssi.html',{'form':form,'compGroups':compGroups},context_instance=RequestContext(request))

#@login_required
def search_flow(request):
#     compGroups = myRetailDatas.get_comp_and_groups()
#     
#     if request.method == 'POST':
#         form = SearchRssiForm(request.POST,error_class=DivErrorList)
#     else:
#         form = SearchRssiForm(error_class=DivErrorList)
#     groups = []
#     comps = []
#     for compGroup in compGroups.values():
#         comps.append([str(compGroup['id']),compGroup['name']])
#         for group in compGroup['groups']:
#             groups.append(["%s:%s"%(compGroup['id'],group['id']),group['name']])
#     form.fields['shop_group'].choices = groups
#     form.fields['comp_group'].choices = comps
#     
   
    logging.debug(request)
    myForm = SearchRssiForm(error_class=DivErrorList)
    if request.method=='POST':
        if request.POST.has_key('company') and request.POST.has_key('group'):
            comp_id = request.POST['company']
            group = request.POST['group']
            startTime = request.POST['startTime']
            endTime = request.POST['endTime']
            walkby_time_list = ['0','60','120']
            opening_weekend = request.POST['opening_weekend']
            opening_weekday = request.POST['opening_weekday']
            count_type = request.POST['count_type']
        else:
            comp_id = 'company'
            group = 'group'
            startTime = ''
            endTime = ''
            walkby_time_list = ['0','60','120']
            opening_weekend = '00:00:00-23:59:59'
            opening_weekday = '00:00:00-23:59:59'
            count_type ='0'
            
    else:
        comp_id = 'company'
        group = 'group'
        startTime = ''
        endTime = ''
        walkby_time_list = ['0','60','120']
        opening_weekend = '00:00:00-23:59:59'
        opening_weekday = '00:00:00-23:59:59'
        count_type ='0'
    if request.POST.has_key('walkby_time'):
        walkby_time_list = dict(request.POST)['walkby_time']    
    
    myForm.initial = {'company':comp_id,'group':group,'startTime':startTime,'endTime':endTime,'walkby_time_list':walkby_time_list,
                      'opening_weekend':opening_weekend,'opening_weekday':opening_weekday,'count_type':count_type
                        }
    if comp_id=='company':comp_id=None
    if group == 'group' : group=None
    companies = myFormDatas.get_companies_data()
    if comp_id!=None:
        groups = myFormDatas.get_groups_data(comp_id=comp_id)
    else:
        groups = []
    myForm.fields['company'].choices +=companies
    myForm.fields['group'].choices +=groups 
    
    
    if re.search('^[\d]{4}-[\d]{2}-[\d]{2}$',startTime) and re.search('^[\d]{4}-[\d]{2}-[\d]{2}$',endTime) and group!='group':
        
        opening_time = {'opening_weekday':opening_weekday,'opening_weekend':opening_weekend}
        

        days = get_slist_between_st_et(startTime,endTime)
        all_datas = mySimilarFlow.get_all_rssi_data(group=group, days=days, walkby_time_list=walkby_time_list, opening_time=opening_time,count_type=count_type)
        #print type(expect_customer_rssi), type(expect_flow_rssi),expect_customer_walkby,treal_flowype(expect_customer_walkby)
        
        if all_datas==None or len(all_datas)==0:
            all_datas = None
            rssiList = []
        else:
            rssiList = all_datas[0]['data'].keys()
            rssiList.sort()
        return render_to_response('zmDataTuning/search_customer_by_rssi_result.html',{'days':days,'all_datas':all_datas,'walkby_time_list':walkby_time_list,'rssiList':rssiList},context_instance=RequestContext(request))
    else:

        return render_to_response('zmDataTuning/search_customer_by_rssi.html',{'form':myForm},context_instance=RequestContext(request))


from employee_rssi import myEmployeeRssi
from base.form_datas import myFormDatas
from base.PyExportFile import myExportFile
from datatuning_datas import myDataTuningDatas


def show_employee_rssi_stat(request):
    myForm = SearchEmployeeRssiForm()
    if request.method=='POST':
        comp_id = request.POST['company']
        group = request.POST['group']
        startTime = request.POST['startTime']
        endTime = request.POST['endTime']
        excluding = request.POST['excluding']
    else:
        comp_id=myForm.fields['company'].choices[0][0]
        group = myForm.fields['group'].choices[0][0]
        startTime = ''
        endTime = ''
        excluding = 20
    initial={'company':comp_id,'group':group,'startTime':startTime,'endTime':endTime,'excluding':excluding}
    myForm = SearchEmployeeRssiForm(initial=initial)
    myForm = myFormDatas.export_base_feild_form(request,myForm,initial)
    
    if re.search('^[\d]{4}-[\d]{2}-[\d]{2}$',startTime) and re.search('^[\d]{4}-[\d]{2}-[\d]{2}$',endTime) and group!=None:
        print group,startTime,endTime
        logging.error("%s,%s,%s"%(group,startTime,endTime))
        #rssiDict = myEmployeeRssi.stat_rssi_data(group=group, st=startTime, et=endTime)
        devices = myRetailDatas.get_devices_by_groups(groups=[group])
        rssiDict = myDataTuningDatas.search_employee_rssi( devices=devices , startTime=startTime,endTime=endTime)
        
        title = myExportFile.get_title_name(prefix='员工Rssi明细',suffix='',
                                      comp_id=comp_id,group=group,
                                      startTime=startTime,endTime=endTime) 
        
        min_rssi,max_rssi = myEmployeeRssi.get_excluding_rssi(excluding=int(excluding), rssiDict=rssiDict)
        avg_rssi = myEmployeeRssi.get_avg_rssi(rssiDict, max_rssi, min_rssi)
        #title = '员工Rssi明细'
        rssi_datas = rssiDict
    else:
        rssi_datas = None
        title = '员工Rssi明细'
        avg_rssi = '-'
        min_rssi = max_rssi = None
        
    print rssi_datas,'--',title
    logging.error(str(rssi_datas))
    #simplejson.dumps(rssi_datas)
    return render_to_response('zmDataTuning/search_employee_rssi.html',{'title':title,'form':myForm,'rssi_datas':rssi_datas,'avg_rssi':avg_rssi,'min_rssi':min_rssi,'max_rssi':max_rssi},context_instance=RequestContext(request))

def show_employee_rssi_stat_by_mac(request):
    myForm = SearchEmployeeRssiForm()
    if request.method=='POST':
        comp_id = request.POST['company']
        group = request.POST['group']
        startTime = request.POST['startTime']
        endTime = request.POST['endTime']
        excluding = request.POST['excluding']
    else:
        comp_id=myForm.fields['company'].choices[0][0]
        group = myForm.fields['group'].choices[0][0]
        startTime = ''
        endTime = ''
        excluding = 20
    initial={'company':comp_id,'group':group,'startTime':startTime,'endTime':endTime,'excluding':excluding}
    myForm = SearchEmployeeRssiForm(initial=initial)
    myForm = myFormDatas.export_base_feild_form(request,myForm,initial)
    
    if re.search('^[\d]{4}-[\d]{2}-[\d]{2}$',startTime) and re.search('^[\d]{4}-[\d]{2}-[\d]{2}$',endTime) and group!=None:
        print group,startTime,endTime
        logging.error("%s,%s,%s"%(group,startTime,endTime))
        #rssiDict = myEmployeeRssi.stat_rssi_data(group=group, st=startTime, et=endTime)
        devices = myRetailDatas.get_devices_by_groups(groups=[group])
        macDict = myDataTuningDatas.search_employee_mac_rssi( devices=devices , startTime=startTime,endTime=endTime)
        
        title = myExportFile.get_title_name(prefix='员工Rssi明细',suffix='',
                                      comp_id=comp_id,group=group,
                                      startTime=startTime,endTime=endTime) 
        rssi_datas = {}
        for mac , rssiDict in macDict.items():
            min_rssi,max_rssi = myEmployeeRssi.get_excluding_rssi(excluding=int(excluding), rssiDict=rssiDict)
            avg_rssi = myEmployeeRssi.get_avg_rssi(rssiDict, max_rssi, min_rssi)
        #title = '员工Rssi明细'
            rssi_datas[mac] = {'min_rssi':min_rssi,'max_rssi':max_rssi,'avg_rssi':avg_rssi,'data':rssiDict}
    else:
        rssi_datas = None
        title = '员工Rssi明细'
        avg_rssi = '-'
        min_rssi = max_rssi = None
        
    print rssi_datas,'--',title
    logging.error(str(rssi_datas))
    #simplejson.dumps(rssi_datas)
    return render_to_response('zmDataTuning/search_employee_mac_rssi.html',{'title':title,'form':myForm,'rssi_datas':rssi_datas},context_instance=RequestContext(request))
  
    

def show_rssi_from_employee(request):
    #print request
    if request.method == 'GET':
        requestDict = dict(request.GET)
    else:
        requestDict = dict(request.POST)


    

    if 'groupList' not in requestDict.keys():
        return HttpResponse(json.dumps( {'code':1004}))
    else:
        groupList = requestDict['groupList']

    if 'startTime' not in requestDict.keys() and 'endTime' not in requestDict.keys():
        startTime = (datetime.date.today()-datetime.timedelta(10)).strftime('%Y-%m-%d')
        endTime = (datetime.date.today()-datetime.timedelta(1)).strftime('%Y-%m-%d')
    elif 'startTime' not in requestDict.keys():
        endTime = requestDict['endTime'][0]
        if not myTimeMethod.check_date_format(endTime):return HttpResponse(json.dumps( {'code':1005}))
        timeList = endTime.split('-')
        startTime = (datetime.date(int(timeList[0]),int(timeList[1]),int(timeList[2])) - datetime.timedelta(9)).strtime('%Y-%m-%d')
    elif 'endTime' not in requestDict.keys():
        
        startTime = requestDict['startTime'][0]
        logging.debug(startTime)
        if not myTimeMethod.check_date_format(startTime):return HttpResponse(json.dumps( {'code':1005}))
        timeList = startTime.split('-')
        endTime = (datetime.date(int(timeList[0]),int(timeList[1]),int(timeList[2])) + datetime.timedelta(9)).strftime('%Y-%m-%d')
    else:
        startTime = requestDict['startTime'][0]
        endTime = requestDict['endTime'][0]
        if not myTimeMethod.check_date_format(endTime):return HttpResponse(json.dumps( {'code':1005}))
        if not myTimeMethod.check_date_format(startTime):return HttpResponse(json.dumps( {'code':1005}))
    

    if 'filterRatio' not in requestDict.keys():
        filterRatio = 20
    else:
        filterRatio = requestDict['filterRatio'][0]
        try:
            filterRatio = int(filterRatio)
        except:
            return HttpResponse(json.dumps( {'code':1005}))
    if 'useSysEmployee' not in requestDict.keys():
        useSysEmployee = 0
    else:
        useSysEmployee = requestDict['useSysEmployee'][0]
        if useSysEmployee not in (0,1,'0','1'):
            return HttpResponse(json.dumps( {'code':1005}))
        useSysEmployee = int(useSysEmployee)
    datas = myEmployeeRssi.get_rssi_from_employee_by_group(groups=groupList,startTime=startTime,endTime=endTime,filterRatio=filterRatio,useSysEmployee=useSysEmployee)
    return HttpResponse(json.dumps( {'code':1000,'dataList':datas}))

if __name__ == '__main__':
    pass